// pages/manage/carDealerManage/carDealerManage.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    screenHeight: app.globalData.screenHeight,
    custMagerTaskStatDealer:{
      carDownNums: 0,
      carSellingNums: 0,
      carTotalNms: 0,
      clearCarActualNums: 0,
      publishCarActualNums: 0,
      thisMonthUserNums: 0,
      todayUserNums: 0,
      userNums: 0
    },

    //车商列表信息。
    carDealerList:[],
    chooseCarDealerId:'',
    chooseCarDealerIndex: 0,



      onReachBottomLoading: false,
      refreshed: false, // 将本属性设置为true，收起下拉刷新，可多次设置为true（即便原来已经是true了）
      userAgreement: true,
      modalName: null,
      searchParams:{
        pageNum: 1,
        pageSize: 6,
        status: '1',
        keyword:'',
        pages:'',
        total:'',
        dealerId:'',
      },
      nocar: true,
      carList:{},
      scopeCar:{},
      operationPageNum:0,
      closeReasonsList:['已经卖给消费者','批发给同行','收到定金了','不便透露'],
      closeReasons:'',
      haveSeeAuth: false,
      userInfo:{},
      topNum:0,
      cangotop: false,
      searchtype:null,
      dealerInfo:{},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function (options) {
    this.InitUserStatus();
  },
  // 检查一下登录状态。
  async InitUserStatus(){
      app.showLoading("获取用户信息");
      await app.checkToken();
      this.InitUserInfo();
      wx.hideLoading();
  },
  InitUserInfo(){
      // this.goQuery();
      this.dealerCustMagerDealerList();
  },
  jumpToMangeDealreMsg(){
    wx.navigateTo({
      url: '/pages/me/manageDealer/manageDealer?id='+this.data.chooseCarDealerId,
    })
  },
  jumpToXiezhu(){
    app.alert('暂未开放');
    return
  },
  // 加载车商列表
  dealerCustMagerDealerList(){
    app.sHttp.dealerCustMagerDealerList().then(res => {
      if(res.carDealerList.length > 0){
        res.carDealerList.forEach(ele =>{
          ele.isShow = true;
        })
        if(this.data.chooseCarDealerId == ''){
          this.setData({
            carDealerList: res.carDealerList,
            chooseCarDealerId: res.carDealerList[0].dealerId,
            chooseCarDealerIndex: 0,
            'searchParams.dealerId': res.carDealerList[0].dealerId,
            dealerInfo:res.carDealerList[0]
          })
          this.custMagerTaskStatDealer();
          this.clearQuery();
        }else{
          let self = this;
          this.setData({
            carDealerList: res.carDealerList,
            dealerInfo: res.carDealerList[self.data.chooseCarDealerIndex]
          })
        }
      }else{
        app.showNoAuthOrNoGrant('您当前没有车商可以管理哦');
      }
    },err =>{
      app.error(err.msg||err);
    })
  },
  chooseTheCarDealer(e){
    let self = this;
    this.setData({
      'searchParams.dealerId': e.currentTarget.dataset.id,
      chooseCarDealerId: e.currentTarget.dataset.id,
      chooseCarDealerIndex: e.currentTarget.dataset.idx,
      dealerInfo:self.data.carDealerList[e.currentTarget.dataset.idx]
    });
    this.hideModal();
    this.custMagerTaskStatDealer();
    this.clearQuery();
  },
  
  // 加载车商的任务
  custMagerTaskStatDealer(){
    app.sHttp.custMagerTaskStatDealer(this.data.chooseCarDealerId).then(res => {
      this.setData({
        'custMagerTaskStatDealer': res.result
      })
    },err =>{
      app.error(err.msg||err);
    })
  },
  searchCarDealerList(e) {
    let key = e.detail.value.toLowerCase();
    let list = this.data.carDealerList;
    for (let i = 0; i < list.length; i++) {
      let a = key;
      let b = list[i].dealerName.toLowerCase();
      if (b.search(a) != -1) {
        list[i].isShow = true
      } else {
        list[i].isShow = false
      }
    }
    this.setData({
      carDealerList: list
    })
  },
  showModal(e) {
      this.setData({
          modalName: e.currentTarget.dataset.target
      })
  },
  hideModal(e) {
      this.setData({
          modalName: null,
          ocrResult:null
      })
  },


  //=======================
  showShareModal(){
    this.selectComponent('#posterComponent').showShareModal('');
    // app.sHttp.shareqrCode({pageUrl:'pages/card/card',scene:'cid='+car.carId}).then(res =>{
    //   let userQrcode = 'data:image/png;base64,' + res.base64;

    // },err=>{
    //   app.error(err.msg);
    // });
  },
  seeBids(){
    let car = this.data.scopeCar;
    this.hideModal();
    wx.navigateTo({
      url: '/pages/garage/offerPrice/offerPrice?cid='+car.carId,
    })
  },
  // 降价一口价
  secondBatch(){
    let car = this.data.scopeCar;
    app.globalData.atttionCar = car;
    this.hideModal();
    wx.navigateTo({
      url: '/pages/garage/secondBatch/secondBatch?cid=' + car.carId,
    })
  },
  // 重新上架
  reShelving(){
    app.sHttp.carManageModifyStatus({carId:this.data.scopeCar.carId,status:1}).then(res =>{
      this.hideModal();
      app.success('上架成功~');
      let self = this;
      setTimeout(() => {
        self.carManageList({pageNum:self.data.operationPageNum,pageSize:6,status:self.data.searchParams.status,keyword:self.data.searchParams.keyword});
      }, 1000);
    },err=>{
      app.error(err.msg);
    })
  },
  // 下架弹窗
  showOffTheShelf(e){
    let car = e.currentTarget.dataset.car;
    if (car.status != 1) {
      this.setData({
        'scopeCar': car
      })
      this.showShareModal();
    }else{
      this.setData({
        'scopeCar': car,
        'operationPageNum': e.currentTarget.dataset.pagenum,
        'modalName': 'offTheShelf'
      });
    }
  },
  offTheShelf(){
    if("" == this.data.closeReasons){
      app.alert('请选择下架原因');
      return;
    }
    app.sHttp.carManageModifyStatus({carId:this.data.scopeCar.carId,status:2,closeReasons:this.data.closeReasons}).then(res =>{
      this.hideModal();
      app.success('下架成功~');
      let self = this;
      if(self.data.userAgreement){
        this.showShareModal();
      }
      setTimeout(() => {
        self.carManageList({pageNum:self.data.operationPageNum,pageSize:6,status:self.data.searchParams.status,keyword:self.data.searchParams.keyword});
      }, 1000);
    },err=>{
      app.error(err.msg);
    })
  },
  carManageDetail(){
    let car = this.data.scopeCar;
    this.hideModal();
    wx.navigateTo({
      url: '/pages/garage/carDetail/carDetail?cid=' + car.carId,
    })
  },
  // 跳转到车辆详情页面
  jumpToCardInfo(e){
    let cid = e.currentTarget.dataset.cid;
    wx.navigateTo({
      url: '/pages/card/card?cid=' + cid+'&self=selfCar',
    })
  },

  carManageList(searchParams){
    this.setData({
      'onReachBottomLoading': true
    })
    app.sHttp.carManageList(searchParams).then(res =>{
      if (searchParams.pageNum == 1 && res.result.carList.length == 0) {
        this.setData({
          'nocar': true,
          'onReachBottomLoading': false
        })
      }else{
        let carList = this.data.carList;
        res.result.carList.forEach(element => {
          if(element.insuranceReportType || element.mtnceReportType){
            element.haveReport = true;
          }else{
            element.haveReport = false;
          }
        });
        carList[searchParams.pageNum] = res.result.carList;
        this.setData({
          'carList': carList,
          'nocar': false,
          'searchParams.pages': res.result.pages,
          'searchParams.total': res.result.total,
          'onReachBottomLoading': false
        })
      }
    },err=>{
      app.error(err.msg);
    })
  },
  onReachBottom(){
    // 触底加载
    let searchParams = this.data.searchParams;
    if (searchParams.pageNum == searchParams.pages || searchParams.pageNum > searchParams.pages) {
      //app.alert('没有更多了哦~');
    }else{
      searchParams.pageNum = searchParams.pageNum+1;
      this.setData({
        'searchParams': searchParams
      });
      this.carManageList(searchParams);
    }
  },
  bindtapInput(e){
    this.setData({
      'searchParams.keyword': e.detail.value
    })
  },
  clearQuery(){
    this.setData({
      'searchParams.keyword': '',
      'searchtype': 0
    });
    this.goQuery();
  },
  switchType(e){
      let type = e.currentTarget.dataset.type;
      let _this = this;
      this.setData({
          'searchParams.status': type
      },(res)=>{
          _this.clearQuery();
      })
  },
  doNothing(){},
  loveHerByOneDay(her){
    if(Object.keys(her).length != 0){
      // 保留里面的 key 为 1 的数据
      let newObj = {};
      newObj[1] = her[1];
      return newObj;
    }else{
      return {};
    }
  },
  goQuery(e){
    let self = this;
    if(undefined  != e && this.data.searchtype != 1){
      if(this.data.searchParams.keyword == ''){
        return;
      }
    }
    let searchtype = undefined ==  e?0:e.currentTarget.dataset.searchtype
    this.setData({
      'searchParams.pageNum':1,
      'searchParams.total':'',
      'searchParams.pages':'',
      'carList': self.loveHerByOneDay(self.data.carList),
      'searchtype': searchtype
    });
    this.carManageList(this.data.searchParams);
  },
  carManageClearCar(e){
    let pageNum = e.currentTarget.dataset.pagenum;
    let index = e.currentTarget.dataset.idx;
    let carId = e.detail;
    if (0 == carId) {
      app.error('请关闭重试');
      return;
    };
    app.sHttp.carManageClearCar(carId).then(res =>{
      let carList = this.data.carList;
      carList[pageNum][index].clearScore = 100;
      carList[pageNum][index].todayIsClear = 1;
      this.setData({
        'carList':carList
      });
      // 重播动画
      this.selectComponent('#barpie'+carId).reloadAnimation();
      // this.goQuery();
    },err=>{
      app.error(err.msg);
    })
  },
  showModal(e) {
    if(this.getTabBar()){
      this.getTabBar().hideTabbar();
    }
      this.setData({
        modalName: e.currentTarget.dataset.target
      });
  },
  hideModal(e) {
    if(this.getTabBar()){
      this.getTabBar().showTabbar();
    }
      this.setData({
        modalName: null
      });
  },
  // 管理车辆
  manageCar(e){
    this.setData({
      'scopeCar': e.currentTarget.dataset.car,
      'operationPageNum': e.currentTarget.dataset.pagenum,
      'modalName': 'manageCar'
    });
  },
  useUserAgreement(){
    this.setData({
      userAgreement: !this.data.userAgreement
    })
  },
  chooseReasons(e){
    this.setData({
      'closeReasons': e.currentTarget.dataset.content
    })
  },
  onPageScroll(e){
    let cangotop = false;
    if (e.scrollTop > 100) {
      cangotop = true;
    }
    if(cangotop != this.data.cangotop){
      this.setData({
        cangotop: cangotop
      })
    }
  },
  jumpToRizhi(e){
    wx.navigateTo({
      url: '/pages/manage/journal/journal?id='+e.currentTarget.dataset.id,
    })
  },
})